package com.project.book.admin.distributed.security.uaa.config;

import com.project.book.admin.distributed.security.uaa.service.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.*;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.Collections;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;
    @Autowired
    private AuthorizationCodeServices authorizationCodeServices;

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private MyUserDetailsService myUserDetailsService;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // /oauth/token_key: 这个endpoint当使用jwttoken且使用非对称加密时，资源服务器用于获取公钥而开放的，这里指这个endpoint完全公开
        security.tokenKeyAccess("permitAll()")
                // oauth/check_token: checkToken这个endpoint完全公开
                .checkTokenAccess("permitAll()")
                // 允许表单认证
                .allowFormAuthenticationForClients();
    }
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // clientDetailsService使用jdbc查询数据库的方式
        // clients.withClientDetails(clientDetailsService);

        // 使用in-memory存储
        clients.inMemory()
                // client_id
                .withClient("c1")
                // 客户端秘钥
                .secret(new BCryptPasswordEncoder().encode("secret"))
                // 客户端可以访问的资源列表
                .resourceIds("res1")
                // 该client允许的授权范围（所有支持的5种）
                .authorizedGrantTypes("authorization_code", "password", "client_credentials", "implicit", "refresh_token")
                // 允许的授权范围（客户端的权限），user-service、read等标识
                .scopes("all")
                // false：授权码模式，跳转到授权的页面，如果是true，不用跳转页面
                .autoApprove(false)
                // 加上验证回调地址
                .redirectUris("http://www.baidu.com")
        .and()
                // client_id
                .withClient("c2")
                // 客户端秘钥
                .secret(new BCryptPasswordEncoder().encode("secret"))
                // 客户端可以访问的资源列表
                .resourceIds("res1")
                // 该client允许的授权范围（所有支持的5种）
                .authorizedGrantTypes("authorization_code", "password", "client_credentials", "implicit", "refresh_token")
                // 允许的授权范围（客户端的权限），user-service、read等标识
                .scopes("read")
                // false：授权码模式，跳转到授权的页面，如果是true，不用跳转页面（默认自动授权，但还是需要登录）
                .autoApprove(true)
                // 加上验证回调地址
                .redirectUris("http://www.baidu.com")

        ;
    }
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // authenticationManager：认证管理器，密码模式
        // authorizationCodeServices：授权码服务
        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(myUserDetailsService)
                .authorizationCodeServices(authorizationCodeServices)
                // 令牌管理服务，都需要
                .tokenServices(tokenService())
                // 允许的POST提交
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);
    }

    /**
     * 令牌管理服务
     * @return
     */
    @Bean
    public AuthorizationServerTokenServices tokenService() {
        DefaultTokenServices service = new DefaultTokenServices();
        // 客户端详情服务
        service.setClientDetailsService(clientDetailsService);
        // 是否产生支持刷新令牌
        service.setSupportRefreshToken(true);
        // 令牌存储策略
        service.setTokenStore(tokenStore);

        // 设置令牌增强
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Collections.singletonList(jwtAccessTokenConverter));
        service.setTokenEnhancer(tokenEnhancerChain);

        // 令牌桶默认有效期2小时
        service.setAccessTokenValiditySeconds(7200);
        // 刷新令牌默认有效期3天
        service.setRefreshTokenValiditySeconds(259200);
        return service;
    }

    /**
     * 设置授权码模式的授权码如何存取，暂时采用内存方式
     * @return
     */
    @Bean
    public AuthorizationCodeServices authorizationCodeServices() {
        // 内存方式
        return new InMemoryAuthorizationCodeServices();
    }
}
